<script setup lang="ts">
import { updatePersonnelAPI } from '@/apis/updatePersonnel'
import { useUserInfoStore } from '@/store/userInfo'

import modalSuccessIcon from '@/static/images/modal/success.png'
import { fetchStaffListAPI } from '@/apis/fetchStaffList'

const router = useRouter()
const userInfoStore = useUserInfoStore()

const projectId = ref('')

const personList = ref<Staff[]>([])
const selectedPersonList = ref<Staff[]>([])

const loading = ref(true)
const isShowSuccessModal = ref(false)

onLoad(async (options) => {
  if (options && options.project_id) {
    projectId.value = options.project_id
    try {
      const res = await fetchStaffListAPI({ group_id: 'worker' }, userInfoStore.userInfo!.token!)
      loading.value = false
      if (res.data?.code === 1)
        personList.value = res.data.data
      else
        uni.showToast({ title: res.data?.msg, icon: 'none' })
    }
    catch {
      uni.showToast({ title: '获取数据失败', icon: 'none' })
    }
  }
  else {
    uni.showToast({ title: '获取数据失败', icon: 'none' })
    loading.value = false
  }
})

const searchText = ref('')

/* ------------------------------- 事件处理 START ------------------------------- */
const handleSearch = useThrottleFn(async (keyword: string) => {
  searchText.value = keyword
  uni.showLoading({ title: '搜索中...' })
  try {
    const res = await fetchStaffListAPI({ group_id: 'worker' }, userInfoStore.userInfo!.token!)
    uni.hideLoading()
    if (res.data?.code === 1)
      personList.value = res.data.data
    else
      uni.showToast({ title: res.data?.msg, icon: 'none' })
  }
  catch {
    uni.showToast({ title: '获取数据失败', icon: 'none' })
  }
}, 500)

function handleSelect(person: Staff) {
  if (selectedPersonList.value.includes(person))
    selectedPersonList.value = selectedPersonList.value.filter(p => p !== person)
  else
    selectedPersonList.value.push(person)
}

const handleSubmit = useThrottleFn(async () => {
  if (selectedPersonList.value) {
    try {
      const res = await updatePersonnelAPI({
        project_id: projectId.value,
        personnel_ids: selectedPersonList.value.map(person => person.id).join(','),
      }, userInfoStore.userInfo!.token!)
      if (res.data?.code === 1)
        isShowSuccessModal.value = true
      else
        uni.showToast({ title: res.data?.msg, icon: 'none' })
    }
    catch {
      uni.showToast({ title: '出现异常，请重试', icon: 'none' })
    }
  }
  else {
    uni.showToast({ title: '出现异常，请重试', icon: 'none' })
  }
}, 500)

function handleExit() {
  router.back()
}
/* -------------------------------- 事件处理 END -------------------------------- */
</script>

<template>
  <view class="relative min-h-screen bg-#F8F8F8">
    <view class="z-100 sticky top-0 left-0 w-750rpx bg-white">
      <Spacer height="30" />
      <view class="mx-30rpx border-1px border-solid border-#E3E3E3 rounded-6rpx">
        <uv-search
          shape="square" bg-color="#F8F9FD" color="#000000" search-icon-size="36rpx"
          search-icon-color="#FF6D0A" placeholder-color="#999999" :show-action="false"
          height="74rpx" placeholder="请输入员工姓名/手机号"
          @change="handleSearch"
        />
      </view>
      <Spacer height="10" />
      <uv-tabs
        :list="[{ name: '全部' }]" line-color="#FF6D0A" line-width="48rpx"
        :active-style="{ color: '#000000', fontSize: '32rpx', lineHeight: '32rpx' }"
        :inactive-style="{ color: '#999999', fontSize: '28rpx', lineHeight: '28rpx' }"
        :custom-style="{ margin: '0 10rpx' }"
      />
    </view>
    <uv-list v-if="personList.length > 0" :custom-style="{ padding: '30rpx 0', backgroundColor: '#F8F8F8' }">
      <uv-list-item v-for="person, index in personList" :key="index" :custom-style="{ borderRadius: '20rpx' }">
        <PersonItem
          :is-show-checkbox="true"
          :is-selected="selectedPersonList.includes(person)"
          :avatar="person.avatar || 'http://jzt.tykhrs.cn/uploads/20240204/87b5977293b9856b96b77b21dcfc3e2a.png'"
          :name="person.nickname || '未知'"
          :identity="person.profession || '未知'"
          :phone-number="person.mobile || '未知'"
          @tap="handleSelect(person)"
        />
        <Divider />
      </uv-list-item>
    </uv-list>
    <PageDefault v-else />
    <uv-loading-page :loading="loading" loading-text="加载中..." font-size="28rpx" loading-mode="spinner" />
    <RGButton class="fixed bottom-80rpx x-center" @tap="handleSubmit">
      确定选择
    </RGButton>
    <uv-overlay :show="isShowSuccessModal" @tap="handleExit">
      <uv-transition mode="zoom-in" :show="isShowSuccessModal">
        <view class="relative w-screen h-screen">
          <JZTModal :icon="modalSuccessIcon" title="分配成功" content="团队人员设置成功" @confirm="handleExit" />
        </view>
      </uv-transition>
    </uv-overlay>
  </view>
</template>

<route lang="yaml">
name: 'assignTeammates'
style:
  navigationBarTitleText: '分配人员'
layout: 'custom'
</route>
